<script lang="ts" setup>
import { all, del, save } from "@/services/category";
import type { Category, CategoryList } from "@/types/category";
import { message } from "ant-design-vue";
import type { FormInstance, Rule } from "ant-design-vue/es/form";
import { onMounted, ref } from "vue";

const columns = [
  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "父分类",
    dataIndex: "parent",
  },
  {
    title: "顺序",
    dataIndex: "sort",
  },
  {
    title: "操作",
    key: "action",
  },
];
const categoryListTree = ref<CategoryList>([]);
const listLoading = ref(false);
const text = ref("");
const open = ref(false);
const formState = ref<Category>({});
const rules: Record<string, Rule[]> = {
  name: [{ required: true, message: "不允许为空", trigger: "change" }],
  parent: [{ required: true, message: "不允许为空", trigger: "change" }],
  sort: [{ required: true, message: "不允许为空", trigger: "change" }],
};
const formRef = ref<FormInstance | null>(null);

// 扁平化数组转树形结构
const attr2Tree = (arr: CategoryList, parent: number) => {
  const data: CategoryList = [];
  arr.forEach((item) => {
    if (item.parent === parent) {
      item.children = attr2Tree(arr, item.id!);
      data.push(item);
    }
  });
  return data;
};

// 加载列表
const loadList = async () => {
  listLoading.value = true;
  try {
    const res = await all();
    categoryListTree.value = attr2Tree(res.content, 0);
  } finally {
    listLoading.value = false;
  }
};

// 打开新增框
const showAddModal = () => {
  text.value = "新增";
  formState.value = {};
  open.value = true;
};

// 打开编辑框，回显数据
const showEditModal = (category: Category) => {
  text.value = "编辑";
  formState.value = Object.assign({}, category);
  open.value = true;
};

// 处理编辑/新增取消
const handleEditOrAddCancel = () => {
  open.value = false;
  // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
  formRef.value?.resetFields();
};

// 处理编辑/新增提交
const handleEditOrAddOk = async () => {
  // 规则校验
  await formRef.value?.validateFields();
  // 发请求
  open.value = false;
  await save(formState.value);
  message.success("success");

  // 请求成功重新加载列表
  loadList();
};

// 删除
const handleDel = async (id: number) => {
  await del(id);
  message.success("success");
  // 请求成功重新加载列表
  loadList();
};

onMounted(() => {
  loadList();
});
</script>
<template>
  <a-layout>
    <a-layout-content
      :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <a-button type="primary" @click="showAddModal" style="margin-bottom: 20px">新增</a-button>

      <a-table
        :columns="columns"
        :data-source="categoryListTree"
        rowKey="id"
        :loading="listLoading"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" @click="showEditModal(record)">编辑</a-button>
              <a-button type="primary" danger
                ><a-popconfirm
                  title="Are you sure delete this task?"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="handleDel(record.id)"
                >
                  <a href="#">删除</a>
                </a-popconfirm></a-button
              >
            </a-space>
          </template>
        </template>
      </a-table>

      <a-modal v-model:open="open" :title="text" @cancel="handleEditOrAddCancel">
        <a-form
          ref="formRef"
          v-if="formState"
          :model="formState"
          :rules="rules"
          name="basic"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
          autocomplete="off"
        >
          <a-form-item label="名称" name="name">
            <a-input v-model:value="formState.name" />
          </a-form-item>
          <a-form-item label="父分类" name="parent">
            <a-select v-model:value="formState.parent">
              <a-select-option :value="0">无</a-select-option>
              <a-select-option
                v-for="item in categoryListTree"
                :key="item.id"
                :value="item.id"
                :disabled="formState.id === item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="顺序" name="sort">
            <a-input v-model:value="formState.sort" />
          </a-form-item>
        </a-form>
        <template #footer>
          <a-button @click="handleEditOrAddCancel">取消</a-button>
          <a-button type="primary" @click="handleEditOrAddOk"> 提交 </a-button>
        </template>
      </a-modal>
    </a-layout-content>
  </a-layout>
</template>
<style scoped></style>
